﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Castle.DynamicProxy;

namespace DotNET4Study
{
    public static class CastleDynamicProxyStudy
    {
        public static void Execute()
        {
            ProxyGenerator proxy = new ProxyGenerator();
            TargetClass target = proxy.CreateClassProxy<TargetClass>(new BeforeInterceptor(), new AfterInterceptor());
            target.OutputWithoutVirtual();
            target.OutputVirtual("QDC");
        }
    }

    public class TargetClass
    {
        public void OutputWithoutVirtual()
        {
            Console.WriteLine("我是正宗的方法,但我不是虚方法，我不能调用拦截器");
        }

        public virtual void OutputVirtual(string departmentName)
        {
            Console.WriteLine("我是正宗的能够调用拦截器的方法");
        }
    }

    public class BeforeInterceptor : IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            ParameterInfo[] paras = invocation.Method.GetParameters();
            string paraString =string.Empty;
             int argLength = paras.Length;
             if (argLength > 0)
             {
                 for (int i = 0; i < argLength; i++)
                 {
                     ParameterInfo para = paras[i];
                     string paraName = para.Name;
                     paraString += paraName+",";
                 }
             }

           string methodName=  invocation.Method.Name;
           Console.WriteLine("我在方法之前运行,方法名称为{0}参数分别为{1}", methodName, paraString);

            invocation.Proceed();
        }
    }

    public class AfterInterceptor : IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            invocation.Proceed();
            Console.WriteLine("我在方法之后运行");
        }
    }
}
